<?php

namespace App\Models\Products;

use App\Models\Concerns\ScopeFilterable;
use App\Models\Currency;
use Illuminate\Database\Eloquent\Model;

/**
 * Class ProductDiscount
 *
 * @property float price - 折扣价格
 * @property int quantity
 *
 * @package App\Models\Products
 */
class ProductDiscount extends Model
{
    const QUANTITY_DEFAULT = 1;  // 默认折扣价的购买数量
    const PRODUCT_DISCOUNT_NUM = 1;  // 起购数为1的折扣数量

    protected $table = 'product_discount';
    protected $guarded = [];

    use ScopeFilterable;

    public $appends = ['symbol_left', 'symbol_right'];

    public $casts = [
        'quantity' => 'int'
    ];

    /**
     * @return mixed|string
     */
    public function getSymbolLeftAttribute()
    {
        $currency = Currency::fromEnv();

       return $currency->symbol_left;
    }

    /**
     * @return mixed|string
     */
    public function getSymbolRightAttribute()
    {
        $currency = Currency::fromEnv();

        return $currency->symbol_right;
    }

    /**
     * @return null|string
     */
    public function getPriceAttribute()
    {
        $currency = Currency::fromEnv();

        $price = $this->attributes['price'];

        if ($price) {
            return $currency->exchangePrice($price);
        } else {
            return null;
        }
    }

    /**
     * @param Product $product
     * @param $quantity
     * @return Product|Model|\Illuminate\Database\Eloquent\Relations\HasMany|null|object
     */
    public static function getProductDiscount(Product $product, $quantity)
    {
        $product_discount = $product->productDiscounts
            ->where('quantity', '<=', $quantity)
            ->sortByDesc('quantity')
            ->sortBy('sort_order')
            ->first();

        return $product_discount;
    }
}
